package com.pvdnc.outguess;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    private static final String TAG=MainActivity.class.getSimpleName();

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    private EditText txtOutputPath;

    private Switch swCompress;

    private ByteArrayOutputStream mStream=new ByteArrayOutputStream();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());

        txtOutputPath =findViewById(R.id.txtOutputPath);
        txtOutputPath.setFocusable(false);
        txtOutputPath.setFocusableInTouchMode(false);

        swCompress=findViewById(R.id.swCompress);

        mImagePicker=new FilePicker(this);
        mDataPicker=new FilePicker(this);

        findViewById(R.id.cmdChooseImage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doAppend();
            }
        });

        findViewById(R.id.cmdCopyPath).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager cm= (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                Objects.requireNonNull(cm);
                ClipData clipData=ClipData.newPlainText("path",
                        txtOutputPath.getText().toString());
                cm.setPrimaryClip(clipData);
                Toast.makeText(MainActivity.this,
                        "输出路径已复制到剪贴板", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK) {
            Log.d(TAG, "handle uri:\n\t" + data.getData());
        }
        mImagePicker.onActivityResult(requestCode, resultCode, data);

        mDataPicker.onActivityResult(requestCode, resultCode, data);
    }

    private boolean shouldCompress(){
        return swCompress.isChecked();
    }

    private FilePicker mImagePicker;
    private FilePicker mDataPicker;

    private void doAppend(){

        mImagePicker.addCallback(new FileCallback("image/*") {
            @Override
            public void onFileReceived(Uri uri, InputStream is) {
                try {
                    byte[] imgData= IOUtils.readIOInputStream(is,false);
                    Log.d(TAG,"imgData ("+imgData.length+"):\n\t"+ Arrays.toString(imgData));
                    //压缩为PNG格式并输出
                    //mStream.write(imgData);
                    ByteArrayOutputStream pngBOS=new ByteArrayOutputStream();
                    Bitmap bmp= BitmapFactory.decodeByteArray(imgData,0,imgData.length);

                    bmp.compress(Bitmap.CompressFormat.PNG,100,pngBOS);
                    imgData= pngBOS.toByteArray();
                    Log.d(TAG,"data ("+imgData.length+"):\n\t"+ Arrays.toString(imgData));
                    //在结果流中写入图片
                    mStream.write(imgData);
                    try {
                        Toast.makeText(MainActivity.this,
                                "选择要隐藏的数据文件", Toast.LENGTH_SHORT).show();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    //打开数据Picker
                    String mime=FileCallback.MIME_ANY;
                    if(!shouldCompress())
                        mime=FileCallback.MIME_ZIP;

                    mDataPicker.open();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        mDataPicker.addCallback(new FileCallback(FileCallback.MIME_ANY) {
            @Override
            public void onFileReceived(Uri uri, InputStream is) {
                try {
                    byte[] data=IOUtils.readIOInputStream(is,false);
                    //压缩
                    if(shouldCompress()) {
                        ByteArrayOutputStream zipBOS = new ByteArrayOutputStream();
                        ZipUtils.compress("hidden_data", data, zipBOS);
                        byte[] zipData = zipBOS.toByteArray();
                        zipBOS.close();
                        IOUtils.IOFile zipFile = new IOUtils.IOFile(
                                getDir("zip", MODE_PRIVATE)
                                        + "/"
                                        + "hidden_data.zip");
                        zipFile.write(zipData, false);
                        mStream.write(zipData);
                    }else{
                        Log.d(TAG,"use raw data ("+data.length+"):"
                                +Arrays.toString(data)
                                +" to append");
                        mStream.write(data);
                    }
                    byte[] finalData=mStream.toByteArray();
                    Log.d(TAG,"finalData ("+finalData.length+")");
                    mStream.reset();
                    //输出到文件
                    File dir= getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                    Objects.requireNonNull(dir);
                    Log.d(TAG,"dir:"+dir+"("+dir.canWrite()+")");
                    IOUtils.IOFile file=new IOUtils.IOFile(
                            dir.getAbsolutePath()
                                    +"/"
                                    +UUID.randomUUID().toString()+".png"/*bypass CoolApk restrict*/
                    );

                    file.write(finalData,false);
                    Log.d(TAG,"file saved on path:"+file.getAbsolutePath());
                    txtOutputPath.setText(file.getAbsolutePath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        mImagePicker.open();
        Toast.makeText(this,
                "选择图像", Toast.LENGTH_SHORT).show();
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
}
